package com.ourcraft.informationcollectionsystem.service.company.fillingFormInfo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ourcraft.informationcollectionsystem.entity.DataReportForm;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import com.ourcraft.informationcollectionsystem.entity.InvestigationPeriod;
import com.ourcraft.informationcollectionsystem.mapper.InvestigationPeriodMapper;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import com.ourcraft.informationcollectionsystem.utils.statusCode.DataReportFormStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Date;

/**
 * FillingFormInfoService provide form information related services interface implementation.
 *
 * @author Xiong Keqin
 * @since 2023-11-04
 */
@Service
public class FillingFormInfoServiceImpl implements FillingFormInfoService {
    @Autowired
    DataReportFormMapper dataReportFormMapper;
    @Autowired
    InvestigationPeriodMapper investigationPeriodMapper;

    /**
     * Retrieves information of list of forms to be filled out by company ID.
     *
     * @param companyId The ID of the company.
     * @return information of list of forms to be filled out.
     */
    @Override
    public List<Map<String, Object>> getAllFillingDataInfo(Integer companyId) {
        // 创建一个空的Map类型的List
        List<Map<String, Object>> data0 = new ArrayList<>();
        // 创建当前时间
        Date currentDate = new Date(new java.util.Date().getTime());

        // 查询需要公司id和当前时间的表单
        List<DataReportForm> dataReportForm = dataReportFormMapper.selectNeedCompanyDataReportForm(companyId, currentDate.getTime());
        // 判断表单是否为空
        if (dataReportForm != null) {
            // 创建日期格式化对象
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // 对每一个表单
            for (DataReportForm item : dataReportForm) {
                // 创建一个空的Map类型的Map
                Map<String, Object> map1 = new HashMap<>();

                // 查找该 formID 对应的 调查开始日期 的信息
                QueryWrapper<InvestigationPeriod> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.lt("investigation_id", item.getInvestigationId())
                        .orderByDesc("investigation_id")
                        .last("LIMIT 1");
                InvestigationPeriod investigationPeriod1 = investigationPeriodMapper.selectOne(queryWrapper1);
                Date dat1;
                String dat1_str;
                if(investigationPeriod1==null) {dat1_str = null;}
                else {
                    dat1 = investigationPeriod1.getInvestigationStartDate();
                    dat1_str = dateFormat.format(dat1);
                }
                // 查找该 formID 对应的 investigationID 的信息
                QueryWrapper<InvestigationPeriod> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("investigation_id", item.getInvestigationId());
                InvestigationPeriod investigationPeriod = investigationPeriodMapper.selectOne(queryWrapper2);
                // 计算提交截止时间
                Date date0 = investigationPeriod.getInvestigationStartDate();//LocalDate.now();
                long millisecondsToAdd = investigationPeriod.getInvestigationLength() * 24 * 60 * 60 * 1000L; // 将天数转换为毫秒
                // 创建一个新的日期
                Date newDate = new Date(date0.getTime() + millisecondsToAdd);
                if(!(currentDate.before(newDate))) continue;

                // 使用日期格式化对象将日期转换为字符串
                String date_str = dateFormat.format(newDate);
                String date_str2 = dateFormat.format(investigationPeriod.getInvestigationStartDate());
                // 添加键值对
                map1.put("formID", item.getFormId());
                map1.put("InvestigationTitle", investigationPeriod.getInvestigationTitle());
                map1.put("investigationID", item.getInvestigationId());
                map1.put("formStartDate", dat1_str);
                map1.put("formEndDate", date_str2);
                map1.put("investigationDescription", investigationPeriod.getInvestigationDescription());
                map1.put("formSubmitDate", date_str);
                map1.put("formExamineStatus", item.getFormExamineStatus());

                data0.add(map1);
            }

            return data0;
        }
        return data0;
    }

    /**
     * Retrieves information of form to be filled out by form ID.
     *
     * @param id The ID of the form.
     * @return information of form to be filled out.
     */
    @Override
    public DataReportForm getFillingFormInfo(Integer id) {
        // 创建一个空的QueryWrapper
        QueryWrapper<DataReportForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", id);
        // 使用MyBatis-Plus的select方法查询数据
        DataReportForm dataReportForm = dataReportFormMapper.selectOne(queryWrapper);
        if (dataReportForm != null) {
            return dataReportForm;
        }
        return dataReportForm;
    }

    /**
     * Update form information.
     *
     * @param da1 The form information.
     * @param is_Submit Whether the identification is submitted information.
     * @return Operation result.
     */
    @Override
    public Boolean submitFillingFormInfo(DataReportForm da1, boolean is_Submit) {
        // 创建一个空的QueryWrapper
        QueryWrapper<DataReportForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", da1.getFormId());

        // 使用MyBatis-Plus的select方法查询数据
        DataReportForm dataReportForm = dataReportFormMapper.selectOne(queryWrapper);
        // 获取状态字段
        DataReportFormStatus status = dataReportForm.getStatus();

        // 设置状态字段
        if (is_Submit)
            da1.setFormExamineStatus(status.submit());
        else da1.setFormExamineStatus(status.save());

        // 创建 UpdateWrapper，并指定更新条件
        UpdateWrapper<DataReportForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("form_id", da1.getFormId());
        // 使用 set 方法指定要更新的字段，即使它们为 null
        updateWrapper.set("form_decrease_type", da1.getFormDecreaseType())
                .set("form_first_reason", da1.getFormFirstReason())
                .set("form_second_reason", da1.getFormSecondReason())
                .set("form_third_reason", da1.getFormThirdReason());

        // 使用MyBatis-Plus的update方法来更新数据
        int rowsUpdated = dataReportFormMapper.update(da1, updateWrapper);

        if (rowsUpdated > 0) {
            return true;
        } else {
            return false;
        }
    }

}
